package com.jsrj.service.impl;

import com.alipay.api.*;
import com.alipay.api.diagnosis.DiagnosisUtils;
import com.alipay.api.domain.*;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.jsrj.BuildStatus;
import com.jsrj.common.core.domain.AjaxResult;
import com.jsrj.domain.BackAlipayMiniDetails;
import com.jsrj.mapper.BackAlipayMiniDetailsMapper;
import com.jsrj.service.IAlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class AlipayServiceImpl implements IAlipayService {

    @Autowired
    private BackAlipayMiniDetailsMapper alipayMiniDetailsMapper;
    /**
     * 支付宝小程序模板构建商家小程序配置
     * @return
     */
    private AlipayConfig getAlipayConfig(){
        AlipayConfig alipayConfig = new AlipayConfig();
        //三方应用id
        alipayConfig.setAppId("2021003127628418");
        //三方应用私钥
        alipayConfig.setPrivateKey("MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDJXoaunsQ/PZJTEXOGYTxHfCsQ7UtCmu2enSQPwqX8eZ6IVOK/ndh2TTYCQ1B3ALN2BeJHVd56eTC6VNdqNowfUpqgFIvhC3WR+RJMTV7Q/WBMzRPm0UM9i/Oe7gx48kbEvuRQMLocAxCUILRwvT779+LOHmamtoMTjWRahdHdRcPwzAb9VWXKxwatteEHZwOomgPjNKBKklFGPnsbcaNT52yvH9J1mAeFNvhA/oWIckCYYJszFdJCXi2ELgjR3EFba4Say+NApPGV3oj69DEV0srtie/YJ/kqRxKzPvtayIMx3fYiszquB9KScH98wkCd8zQTIo4ZoLyeLYVKkT8NAgMBAAECggEBAKM+jz62lO+TsbDH3/ibkSt+fMc/J5j6UhIY4CgqqzdPPPbWoe+nPdlB5LvW6D9hARt3z6X29eIhpyAXMX74c4XdCF8n6PHqwUgyO+RBgNE55zy7sBuZn8IgV8KKxu+xsS9EdYCQz/9veJwtGzqeIJZRsbtZJ+yU3xQVtrov7B9NRCoXgw3/BFb01jmHvMgl+9GwL4NPWww4dP/yZ6BWZEzJ/AtHklrtiY5T5qUYectpUXDN8zUdbgZIBdid5dyhPVl3fZVIfVvox9nL1JlxV68JO74IeY2tA1lYkJQTSkU+tIAw7lvtp+YPWXwt1Wg4uL7XcVnao2Ts/PJCF1FvGb0CgYEA6jf8v+QsmW1eaRJGHNeS0cGu09i24MN+NqxZ91j6yh4tEyjG4kxh6oX1oFelUNKsMBQNeX7bTJ4v+QG0PUA4R1yas+QXwbiWlht162itsmXdSERRm1uNN5pXfgigCwQ3p3hEC4dgz7z8mPR+9AyNOey4npAIz7l0gWgYcrB+a88CgYEA3Bh/CQKNAZb4GVHDM4mFVg539nylX5qRF/4OjZEB6nMPjO++UzsfQwUsyH1z8a5VXIcLl4eO80+WXXuXZv7WBDAV0L5iSBFN8CYj35otjJFHwMFXF9OPgAPW65LwUiou4YWpNSOst25ioRr2NzxF7LVct5KHgcpa+JIdX0GXEmMCgYEA2EDFTu9/9lEy4FSNA8hOuPjZUKRBhhk6CYTstCIlvERMXepCZ2Ma7Qyuk1MZQhyh+uoo3sqv9HgB1ykpn3wR+mGYPQwWmzixYPsNz0MhTRwcScM6jfTj2DjbG3UfP8yvDiNOwE5IpsXZe+gS54ZHRvo4I77dQ935ohnYqNwofaUCgYA7thmg5CRFLiQZGmmO7dxSwJIjOSXUjiaXD8H6/kA6zwSFA/XqtruAf0LrEb4G73kRJUIr1gceU5VDv2gP9Usyz6jbfQtE6gzu/in1W+rHnBKPZOSv/iGMZX5FYxP39qHJZW3GkOsmyLfRZXMvARcnZPzGgOZqe++6SEnXsf++aQKBgEDPpMfaPq4bMBzluym6R/3cGcesB282g93nYWPTYMjH4ND75B0fDan+59HQT3BhtnecxFi18k92DIL9ORP88Qc26t6zB4SAWTTg3byOCjnYJ/KD3HBTJjdhZQ9AwbwvOG6h9qL1T29Yof8bPpUtqiz3RSvKA9ibTzvNaylYw179");
        //三方应用支付宝公钥
        alipayConfig.setAlipayPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjyifr2E9lOQkL31KGSe75nEAFVq3FNGO6HjfLjKU67v+umro/J0z4iWe4ZxfcZbjkX1Hwpt7qcL1eF7CIH7yKDWLMBCw/iFJhZm4lgAfPz2qLb/0KgFSCVu9d83JEsydWQAyit/jO66Ykr9kx3+C+pWQ5jqqDT7ud7Le9slh2OfV24JSgKCUsA2FPDZh92O3EBJutPsSDYv0QtSQj74k+zAnvUXkfucP1FGGIXSm/WiaSU9LAF97QBa4KXzNZ1RvTSqOyGQqJ4KBYzf9koqGY44kbn8k7dut4XYuJUxWv9+gg1JskVtHTF0uxOMnvxU458ZBjK9ZufunxddP2ibzQwIDAQAB");
        return alipayConfig;
    }

    /**
     * 公共方法返回请求结果
     * @param success
     * @param body
     * @param diagnosisUrl2
     * @return
     */
    private AjaxResult getAjaxResult(boolean success, AlipayResponse body, String diagnosisUrl2) {
        if (success) {
            System.out.println("调用成功");
            System.out.println(body);
            return AjaxResult.success(body);
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            String diagnosisUrl = diagnosisUrl2;
            System.out.println(diagnosisUrl);
            return AjaxResult.error(diagnosisUrl);
        }
    }
    /**
     * 基于模板上传小程序版本
     * @return
     * @throws AlipayApiException
     */
    @Override
    public AjaxResult uploadMiniVersion() throws AlipayApiException {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());
        AlipayOpenMiniVersionUploadRequest request = new AlipayOpenMiniVersionUploadRequest();

        AlipayOpenMiniVersionUploadModel model = new AlipayOpenMiniVersionUploadModel();
        //设置小程序模板appId
        model.setTemplateId("2021004149696817");
        //设置商家小程序版本
        model.setAppVersion("0.0.1");
        // 设置小程序端
        model.setBundleId("com.alipay.alipaywallet");
        request.setBizModel(model);
        //重点！！！
        request.putOtherTextParam("app_auth_token","202406BB3a53294c52834ed095dcc2d3357d1C68");

        AlipayOpenMiniVersionUploadResponse response = alipayClient.execute(request);

        return getAjaxResult(response.isSuccess(), response, DiagnosisUtils.getDiagnosisUrl(response));
    }

    /**
     * 查询商家小程序构建状态
     * @return
     * @throws AlipayApiException
     */
    @Override
    public AjaxResult queryMiniVersion() throws AlipayApiException {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayOpenMiniVersionBuildQueryRequest request = new AlipayOpenMiniVersionBuildQueryRequest();
        AlipayOpenMiniVersionBuildQueryModel model = new AlipayOpenMiniVersionBuildQueryModel();

        // 设置小程序版本号
        model.setAppVersion("0.0.1");

        // 设置小程序端
        model.setBundleId("com.alipay.alipaywallet");
        request.setBizModel(model);

        //重点！！！
        request.putOtherTextParam("app_auth_token","202406BB3a53294c52834ed095dcc2d3357d1C68");

        AlipayOpenMiniVersionBuildQueryResponse response = alipayClient.execute(request);
        response.setBuildStatus(BuildStatus.getDescriptionByValue(response.getBuildStatus()));
        return getAjaxResult(response.isSuccess(), response, DiagnosisUtils.getDiagnosisUrl(response));
    }

    /**
     * 小程序版本详情查询
     * @return
     * @throws AlipayApiException
     */
    @Override
    public AjaxResult queryDetailMiniVersion() throws AlipayApiException {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayOpenMiniVersionDetailQueryRequest request = new AlipayOpenMiniVersionDetailQueryRequest();
        AlipayOpenMiniVersionDetailQueryModel model = new AlipayOpenMiniVersionDetailQueryModel();

        // 设置小程序版本号
        model.setAppVersion("0.0.1");

        // 设置小程序端
        model.setBundleId("com.alipay.alipaywallet");

        request.setBizModel(model);
        //重点！！！
        request.putOtherTextParam("app_auth_token","202406BB3a53294c52834ed095dcc2d3357d1C68");
        AlipayOpenMiniVersionDetailQueryResponse response = alipayClient.execute(request);
        return getAjaxResult(response.isSuccess(), response, DiagnosisUtils.getDiagnosisUrl(response));
    }
    /**
    *@auther 崔宏江
    *@describe 支付宝小程序基本信息获取
    *@data 2024/7/2 16:07
    */
    @Override
    public AjaxResult queryMiniBaseInfo() throws AlipayApiException {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayOpenMiniBaseinfoQueryRequest request = new AlipayOpenMiniBaseinfoQueryRequest();

        //重点！！！
        request.putOtherTextParam("app_auth_token","202406BB3a53294c52834ed095dcc2d3357d1C68");

        AlipayOpenMiniBaseinfoQueryResponse response = alipayClient.execute(request);

        return getAjaxResult(response.isSuccess(), response, DiagnosisUtils.getDiagnosisUrl(response));
    }

    /**
    *@auther 崔宏江
    *@describe 支付宝小程序类目树查询
    *@data 2024/7/2 16:27
    */
    @Override
    public AjaxResult queryMiniCategory() throws AlipayApiException {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayOpenMiniCategoryQueryRequest request = new AlipayOpenMiniCategoryQueryRequest();
        AlipayOpenMiniCategoryQueryModel model = new AlipayOpenMiniCategoryQueryModel();

        // 设置是否过滤
        model.setIsFilter(true);

        request.setBizModel(model);
        // 第三方代调用模式下请设置app_auth_token
        request.putOtherTextParam("app_auth_token","202406BB3a53294c52834ed095dcc2d3357d1C68");

        AlipayOpenMiniCategoryQueryResponse response = alipayClient.execute(request);

        return getAjaxResult(response.isSuccess(), response, DiagnosisUtils.getDiagnosisUrl(response));
    }
    /**
    *@auther 崔宏江
    *@describe 支付宝小程序类目所需资质获取
    *@data 2024/7/2 17:32
    */
    @Override
    public AjaxResult queryMiniCategoryRequire(Long id) throws AlipayApiException {
        //获取要提审小程序的信息
        BackAlipayMiniDetails alipayMiniDetails  =  alipayMiniDetailsMapper.selectBackAlipayMiniDetailsById(id);
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayOpenMiniCategoryRequireQueryRequest request = new AlipayOpenMiniCategoryRequireQueryRequest();
        AlipayOpenMiniCategoryRequireQueryModel model = new AlipayOpenMiniCategoryRequireQueryModel();

        // 使用split方法分割字符串
        String[] strArray = alipayMiniDetails.getMiniCategoryIds().split(";");

        // 使用Arrays.asList将数组转换为List
        List<String> list = Arrays.asList(strArray);
        ArrayList<String> categoryCodeList = new ArrayList<>(list);

        // 设置类目列表
        model.setCategoryCodeList(categoryCodeList);

        request.setBizModel(model);
        // 第三方代调用模式下请设置app_auth_token
        request.putOtherTextParam("app_auth_token","202406BB3a53294c52834ed095dcc2d3357d1C68");
        AlipayOpenMiniCategoryRequireQueryResponse response = alipayClient.execute(request);

        return getAjaxResult(response.isSuccess(), response, DiagnosisUtils.getDiagnosisUrl(response));
    }
    /**
    *@auther 崔宏江
    *@describe 支付宝小程序提交审核
    *@data 2024/7/2 18:04
    */
    @Override
    public AjaxResult auditMiniVersion(Long id) throws AlipayApiException {
        //获取要提审小程序的信息
        BackAlipayMiniDetails alipayMiniDetails  =  alipayMiniDetailsMapper.selectBackAlipayMiniDetailsById(id);
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayOpenMiniVersionAuditApplyRequest request = new AlipayOpenMiniVersionAuditApplyRequest();

        // 设置小程序版本号
        request.setAppVersion(alipayMiniDetails.getAppVersion());

        // 设置小程序版本描述
        request.setVersionDesc(alipayMiniDetails.getVersionDesc());

        // 设置小程序简介
        request.setAppSlogan(alipayMiniDetails.getAppSlogan());

        // 设置区域类型
        request.setRegionType(alipayMiniDetails.getRegionType());

        // 设置小程序客服电话
        request.setServicePhone(alipayMiniDetails.getServicePhone());

        // 设置小程序描述
        request.setAppDesc(alipayMiniDetails.getAppDesc());

        // 设置营业执照有效期
        request.setLicenseValidDate(alipayMiniDetails.getLicenseValidDate());

        // 设置新小程序前台类目
        request.setMiniCategoryIds(alipayMiniDetails.getMiniCategoryIds());

        // 设置小程序名称
        request.setAppName("迅捷救援");

        // 设置小程序logo图标
//        FileItem appLogo = new FileItem(alipayMiniDetails.getAppLogo());
        FileItem appLogo = new FileItem("E:\\project\\photo\\alipay-head.jpg");
        request.setAppLogo(appLogo);

        // 设置营业执照名称
        request.setLicenseName(alipayMiniDetails.getLicenseName());

        // 设置营业执照证件号
        request.setLicenseNo(alipayMiniDetails.getLicenseNo());

        // 设置第一张营业执照照片
        FileItem firstLicensePic = new FileItem("E:\\CMS\\img\\upload\\2024\\07\\02\\昆区.jpg");
        request.setFirstLicensePic(firstLicensePic);

        // 设置门头照
//        FileItem outDoorPic = new FileItem("outDoorPic.jpg",Base64.getDecoder().decode(imageBase64));
//        request.setOutDoorPic(outDoorPic);

        // 设置第一张特殊资质图片
//        FileItem firstSpecialLicensePic = new FileItem("firstSpecialLicensePic.jpg",Base64.getDecoder().decode(imageBase64));
//        request.setFirstSpecialLicensePic(firstSpecialLicensePic);

//        设置省市区信息，当region_type为LOCATION时
//        request.setServiceRegionInfo();

        //重点！！！
        request.putOtherTextParam("app_auth_token","202406BB3a53294c52834ed095dcc2d3357d1C68");

        AlipayOpenMiniVersionAuditApplyResponse response = alipayClient.execute(request);

        return getAjaxResult(response.isSuccess(), response, DiagnosisUtils.getDiagnosisUrl(response));
    }

    /**
    *@auther 崔宏江
    *@describe 退回开发
    *@data 2024/7/3 10:04
    */
    @Override
    public AjaxResult auditedMiniVersion(Long id) throws AlipayApiException {
        //获取要提审小程序的信息
        BackAlipayMiniDetails alipayMiniDetails  =  alipayMiniDetailsMapper.selectBackAlipayMiniDetailsById(id);
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayOpenMiniVersionAuditedCancelRequest request = new AlipayOpenMiniVersionAuditedCancelRequest();
        AlipayOpenMiniVersionAuditedCancelModel model = new AlipayOpenMiniVersionAuditedCancelModel();

        // 设置商家小程序版本号
        model.setAppVersion(alipayMiniDetails.getAppVersion());

        // 设置小程序端
        model.setBundleId("com.alipay.alipaywallet");

        request.setBizModel(model);
        //重点！！！
        request.putOtherTextParam("app_auth_token","202406BB3a53294c52834ed095dcc2d3357d1C68");
        AlipayOpenMiniVersionAuditedCancelResponse response = alipayClient.execute(request);

        return getAjaxResult(response.isSuccess(), response, DiagnosisUtils.getDiagnosisUrl(response));
    }
}
